package com.ckzp.jfinal.system.controller;

import com.ckzp.core.util.DateUtil;
import com.ckzp.jfinal.base.PageSearch;
import com.ckzp.jfinal.form.FormSelect;
import com.ckzp.jfinal.plugins.cron4j.MyCron4jPlugin;
import com.ckzp.jfinal.plugins.tree.TreeNode;
import com.ckzp.jfinal.system.cache.SysTypeCache;
import com.ckzp.jfinal.system.cache.SysUserCache;
import com.ckzp.jfinal.system.model.SysCode;
import com.ckzp.jfinal.system.model.SysWorklog;
import com.ckzp.plugins.layui.LayuiData;
import com.ckzp.core.json.JsonResult;
import com.ckzp.core.model.Datas;
import com.ckzp.jfinal.base.BaseController;
import com.ckzp.jfinal.form.FormData;
import com.ckzp.jfinal.interceptor.Admins;
import com.ckzp.jfinal.plugins.UpImage;
import com.ckzp.jfinal.system.model.SysTask;
import com.ckzp.jfinal.system.util.SysTaskUtil;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;

import java.util.Date;
import java.util.List;

/**
 * Created by wuyang(51594) on 2022-03-29 15:17:49.
 */
public class SysTaskController extends BaseController {

    @Admins(roles = "login", name = "默认", log = false)
    public void index() {
        renderText("默认");
    }


    /**
     * 列表显示页面
     */
    @Admins(roles = "system", name = "列表Page", log = false)
    public void SysTaskList() {
        FormData fd = FormData.dao();
        setAttr("form", fd);
        render("SysTaskList.html");
    }

    /**
     * 列表数据查询API
     * fd.addSelect("", SysDataCache.getFormSelect(""));
     */
    @Admins(roles = "system", name = "列表数据查询Api", log = false)
    public void SysTaskListDataApi() {
        PageSearch ps = PageSearch.n().setTable("sys_task").init(getRequest())
                .orderby(getRequest(), "task_id desc");
        Page<SysTask> pages = ps.paginate(SysTask.dao);
        List<SysTask> datalist = pages.getList();
        for (SysTask task : datalist) {
            int task_id = task.mod.getInt("task_id");
            String name = "task_" + task_id;
            task.put("is_auto_str", task.mod.getInt("is_auto") == 1 ? "<font color=green>是</font>" : "<font color=red>否</font>");
            task.put("is_log_str", task.mod.getInt("is_log") == 1 ? "<font color=green>是</font>" : "<font color=red>否</font>");
            if (MyCron4jPlugin.getTaskStatus(name)) {
                task.put("run", 1);
                task.put("status", "运行中");
                task.put("status_color", "green");
                task.put("task_action", "<button value=\"" + task_id + "\" class=\"layui-btn layui-btn-sm btn-change-13\" lay-event=\"StopTask\">停止运行</button>");
            } else {
                task.put("run", 0);
                task.put("status", "停止");
                task.put("status_color", "red");
                task.put("task_action", "<button value=\"" + task_id + "\" class=\"layui-btn layui-btn-sm btn-change-4\" lay-event=\"StartTask\">启动运行</button>");
            }
        }
        renderJson(LayuiData.newData().setData(datalist).setCount(pages.getTotalRow()));
    }

    /**
     * 任务日志显示页面
     */
    @Admins(roles = "system", name = "列表Page", log = false)
    public void SysTaskLogList() {
        FormData fd = FormData.dao();
        setAttr("form", fd);
        render("SysTaskLogList.html");
    }


    /**
     * 登陆日志查询API
     */
    @Admins(roles = "system", name = "登陆日志查询API", log = false)
    public void SysTaskLogListDataApi() {
        PageSearch ps = PageSearch.n().init(getRequest(), "sys_worklog");
        ps.search("log_type", 98);
        ps.orderby(getRequest(), "log_id desc");
        Page<SysWorklog> pages = ps.paginate(SysWorklog.dao);
        List<SysWorklog> datalist = pages.getList();
        FormSelect fs = FormSelect.n().setSource("`1`成功`2`失败`").setColor("`1`layui-bg-green`2`layui-bg-orange`").setReadOnly(true);
        for (SysWorklog wl : datalist) {
            wl.put("emp_str", SysUserCache.transUserName(wl.mod.getInt("emp_id")));
            wl.put("log_result_str", fs.showText(wl.mod.getInt("log_result")));
            wl.put("log_result_color", wl.mod.getInt("log_result") == 1 ? "layui-bg-green" : "");
        }
        renderJson(LayuiData.newData().setData(datalist).setCount(pages.getTotalRow()));
    }

    /**
     * 添加定时任务Page
     */
    @Admins(roles = "system", name = "添加PAGE", log = false)
    public void AddSysTask() {
        FormData fd = FormData.dao().setActions("ADD");
        setAttr("task", new SysTask());
        setAttr("form", fd);
        render("ModifySysTask.html");
    }

    /**
     * 修改定时任务Page
     * fd.addSelect("", SysDataCache.getFormSelect("").setLayFilter("").showHtml(o.mod.getStr("")));
     */
    @Admins(roles = "system", name = "修改定时任务Page", log = false)
    public void EditSysTask() {
        String task_id = getPara("task_id", "");
        SysTask o = SysTask.dao.findById(task_id);
        FormData fd = FormData.dao().setActions("EDIT");
        if (o != null) {
            o.put("is_auto_status", o.mod.getInt("is_auto") == 1 ? "checked" : "");
            o.put("is_log_status", o.mod.getInt("is_log") == 1 ? "checked" : "");
        }
        setAttr("form", fd);
        setAttr("task", o);
        render("ModifySysTask.html");
    }

    /**
     * 修改定时任务Api
     */
    @Admins(roles = "system", name = "修改定时任务Api", log = true)
    public void ModifySysTaskApi() {
// 取得数据
        Datas data = getParaData("postdata", "");
        String task_id = data.getStr("task_id");//主键
        String actions = data.getStr("actions");//action
        if ("EDIT".equals(actions)) {//修改
            boolean results = SysTask.dao.findById(task_id)
                    .set("task_name", data.getStr("task_name"))
                    .set("task_cron", data.getStr("task_cron"))
                    .set("is_auto", data.getInt("is_auto", 0))
                    .set("is_log", data.getInt("is_log", 0))
                    .set("task_class", data.getStr("task_class"))
                    .set("task_desc", data.getStr("task_desc"))
                    .update();
            renderJson(Json(results, "修改"));
        } else {//添加
            boolean results = new SysTask()
                    .set("task_id", data.getInt("task_id"))
                    .set("task_name", data.getStr("task_name"))
                    .set("task_cron", data.getStr("task_cron"))
                    .set("is_auto", data.getInt("is_auto", 0))
                    .set("is_log", data.getInt("is_log", 0))
                    .set("task_class", data.getStr("task_class"))
                    .set("task_desc", data.getStr("task_desc"))
                    .save();
            renderJson(Json(results, "添加"));
        }
    }

    /**
     * 修改定时任务字段Api
     * demo:
     * fd.addSelect("", SysDataCache.getFormSelect("").setLayFilter("").showHtml(o.mod.getStr("")));
     */
    @Admins(roles = "system", name = "修改定时任务字段Api", log = true)
    public void ModifySysTaskFieldApi() {
        String task_id = getParaStr("key_id", "");
        String field = getPara("field", "");
        String value = getPara("values", "");
        SysTask o = SysTask.dao.findById(task_id);
        if (o != null) {
            boolean status = o.set(field, value).update();
            renderJson(JsonResult.n(status ? 0 : 9, "修改" + (status ? "成功" : "失败")));
        } else {
            renderJson(JsonResult.n(0, "修改成功"));
        }
    }


    /**
     * 删除定时任务Api
     */
    @Admins(roles = "system", name = "删除定时任务Api", log = true)
    public void DelSysTaskApi() {
        int task_id = getInt("task_id", 0);
        SysTask task = SysTask.dao.findById(task_id);
        if (task == null) {
            renderJson(JsonResult.n(9, "记录不存在"));
        } else if (task.delete()) {
            renderJson(JsonResult.n(0, "删除成功"));
        } else {
            renderJson(JsonResult.n(9, "删除失败"));
        }
    }

    /**
     * 马上执行定时任务Api
     */
    @Admins(roles = "system", name = "删除定时任务Api", log = true)
    public void RunSysTaskApi() {
        int task_id = getInt("task_id", 0);
        renderJson(SysTaskUtil.n().runSysTask(task_id));

    }


    /**
     * 启动定时任务Api
     */
    @Admins(roles = "system", name = "删除定时任务Api", log = true)
    public void StartSysTaskApi() {
        int task_id = getInt("task_id", 0);
        renderJson(SysTaskUtil.n().startTask(task_id));
    }


    /**
     * 关闭定时任务Api
     */
    @Admins(roles = "system", name = "删除定时任务Api", log = true)
    public void StopSysTaskApi() {
        int task_id = getInt("task_id", 0);
        renderJson(SysTaskUtil.n().stopTask(task_id));
    }

    /**
     * 图片上传接口
     */
    @Admins(roles = "system", name = "图片上传API", log = false)
    public void UploadImages() {
        renderJson(UpImage.n().upload(getRequest(), "show", true, true));
    }


    /**
     * 改变定时任务字段状态Api(0 or 1)
     */
    @Admins(roles = "system", name = "改变定时任务字段状态Api", log = true)
    public void ChangeTagApi() {
        String keyid = getParaStr("key", "");
        String field = getParaStr("field", "");
        String msg = getParaStr("msg", "");
        renderJson(DoBasePub(SysTask.dao, keyid, field, msg));
    }


    /**
     * 清空操作日志Api
     */
    @Admins(roles = "system", name = "清空任务日志Api", log = false)
    public void EmptyTaskLogApi() {
        int days = getParaInt("days", 365);
        if (days < 1) days = 1;
        Date log_time = DateUtil.addDay(new Date(), (-1 * days));
        Db.delete("delete from sys_worklog where log_type=98 and log_time<?", log_time);
        renderJson(JsonResult.n(0, "清除任务日志成功"));
    }

    /**
     * 批量删除任务日志Api
     */
    @Admins(roles = "system", name = "批量删除任务日志Api", log = false)
    public void DelMoreyTaskLogApi() {
        renderJson(DelMoreModel(SysWorklog.dao, getParaStr("keys", ""), "删除任务日志"));
    }
}